package org.bear.linkList;

public class RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0; i < n-1; i++) {
            fast = fast.next;
            if (fast == null) {
                return head;
            }
        }
        if (fast.next==null){
            return head.next;
        }
        fast = fast.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }


    public static void main(String[] args) {
        ListNode head = ListNode.generate(new int[]{1, 2, 3, 4, 5});
        RemoveNthFromEnd r = new RemoveNthFromEnd();
        ListNode result = r.removeNthFromEnd(head, 5);
        System.out.println(result);
    }


}
